/*
 * @Author: Wilbur
 * @Date: 2019-08-22 10:27:44
 * @Last Modified by: Wilbur
 * @Last Modified time: 2019-08-23 16:30:04
 */

<template>
    <div class="container jingang-list-container">
        <div class="operation-wrapper">
            <el-input
                placeholder="搜索店铺名称"
                style="width: 375px;"
                size="medium"
                @keyup.native.enter="getTableData(1)"
                v-model="keyword">
                <i
                    slot="prefix"
                    class="el-input__icon el-icon-search"/>
            </el-input>
        </div>
        <div class="content-wrapper">
            <div class="table-wrapper">
                <el-table
                    :data="tableData"
                    height="100%"
                    style="width: 100%;">
                    <el-table-column
                        fixed="left"
                        header-align="left"
                        align="center"
                        :width="50"
                        label="序号">
                        <template slot-scope="scope">
                            <div class="table-index">
                                {{ scope.$index + 1 }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="shop_type"
                        fixed="left"
                        show-overflow-tooltip
                        width="100px"
                        label="绑定状态">
                        <template slot-scope="scope">
                            <template v-if="scope.row.action_type == 1">已绑定</template>
                            <template v-if="scope.row.action_type != 1">未绑定</template>
                        </template>
                    </el-table-column>
                    <el-table-column
                        fixed="left"
                        prop="seller_id"
                        width="120"
                        show-overflow-tooltip
                        :formatter="emptyFormatter"
                        label="店铺ID"/>
                    <el-table-column
                        fixed="left"
                        prop="seller_title"
                        show-overflow-tooltip
                        :formatter="emptyFormatter"
                        label="店铺名称"/>
                    <el-table-column
                        prop="shop_logo"
                        show-overflow-tooltip
                        label="品牌logo">
                        <template slot-scope="scope">
                            <img
                                class="sub-logo"
                                :src="scope.row.seller_logo"
                                alt="">
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="date"
                        label="操作"
                        :width="100"
                        fixed="right">
                        <template slot-scope="scope">
                            <div>
                                <el-button
                                    v-if="scope.row.action_type == 1"
                                    type="text"
                                    style="margin-left:10px;"
                                    @click="fnBindHireShop(scope.row, 0)">
                                    解绑
                                </el-button>
                                <el-button
                                    v-if="scope.row.action_type != 1"
                                    type="text"
                                    style="margin-left:10px;"
                                    @click="fnBindHireShop(scope.row, 1)">
                                    绑定
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="pagination-wrapper clearfix">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :total="page.total_count"
                    :page-size="page.page_size"
                    @current-change="getTableData" />
            </div>
        </div>
        <!-- 添加课程分类弹窗 -->
        <el-dialog
            title="分类"
            width="475px"
            :visible.sync="dialogAddVisible">
            <el-form
                :model="ruleForm"
                :rules="rules"
                ref="ruleForm"
                label-width="80px"
                class="demo-ruleForm">
                <el-form-item
                    label="分类名称"
                    prop="cate_name">
                    <el-input
                        v-model="ruleForm.cate_name"
                        class="add-dialog-input"/>
                </el-form-item>

                <el-form-item
                    label="图标"
                    prop="cate_logo">
                    <el-upload
                        :show-file-list="false"
                        :http-request="e=> {fnUploadImageOfGoods(e)}"
                        accept="image/*"
                        class="upload-good-image"
                        action="https://jsonplaceholder.typicode.com/posts/">
                        <img
                            v-if="ruleForm.cate_logo"
                            :src="ruleForm.cate_logo"
                            class="avatar">
                        <i
                            v-else
                            class="el-icon-plus avatar-uploader-icon"/>
                    </el-upload>
                </el-form-item>

                <el-form-item
                    label="排序号"
                    prop="cate_sort">
                    <el-input
                        v-model="ruleForm.cate_sort"
                        type="number"
                        class="add-dialog-input"/>
                </el-form-item>
            </el-form>
            <div
                slot="footer"
                class="dialog-footer">
                <el-button @click="dialogAddVisible = false">取 消</el-button>
                <el-button
                    type="primary"
                    @click="submitForm('ruleForm')">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 设置权限弹窗 -->
        <el-dialog
            title="提示"
            :visible.sync="centerDialogVisible"
            width="30%"
            custom-class="auth-dialog"
            center>
            <div class="dialog-auth">
                <div class="auth-title">该商家提交商品是否需要审核？</div>
                <div class="radio-wrap-dialog">
                    <el-radio-group v-model="authValue">
                        <el-radio :label="1">需要审核</el-radio>
                        <el-radio :label="0">无需审核</el-radio>
                    </el-radio-group>
                </div>
            </div>
            <span
                slot="footer"
                class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button
                    type="primary"
                    @click="fnConfirmSetShopAuth">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 绑定弹窗 -->
        <el-dialog
            title="确认绑定？"
            :visible.sync="bindDialogFlag">
            <el-form
                :model="formBind"
                ref="formBind"
                :rules="rulesBind">
                <el-form-item
                    label="账户"
                    prop="hire_no"
                    :label-width="formLabelWidth">
                    <el-select
                        v-model="formBind.hire_no"
                        filterable
                        remote
                        placeholder="请输入关键词"
                        :remote-method="remoteMethod"
                        :loading="loading">
                        <el-option
                            v-for="item in optionsShop"
                            :key="item.hire_no"
                            :label="item.company_name"
                            :value="item.hire_no"/>
                    </el-select>
                    <div class="hire-count-name">{{ fnComputedName(formBind.hire_no) }}</div>
                </el-form-item>
            </el-form>
            <div
                slot="footer"
                class="dialog-footer">
                <el-button @click="fnCloseBindDialog">取 消</el-button>
                <el-button
                    type="primary"
                    @click="fnBindDialog('formBind')">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        var checkTypeLogo = (rule, value, callback) => {
            if (this.ruleForm.cate_logo == '') {
                return callback(new Error('请上传分类图片'));
            }else{
                callback();
            }
        };

        return {
            authResult: {},
            tableData: [],
            filterData: {
            },
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 0
            },
            baseUrl: '',
            mobileUrl: '',
            escape: escape,
            sessionTicket: localStorage.getItem('sessionTicket'),
            dialogAddVisible: false,
            centerDialogVisible: false,
            bindDialogFlag: false,
            typeList: [],
            selectList: [],
            ruleForm: {
                cate_name: '',
                type: '1',
                cate_sort: '',
                cate_no: '',
                cate_logo: ''
            },
            typeDisabled: false,
            rules: {
                cate_name: [
                    { required: true, message: '请输入分类名称', trigger: 'blur' }
                ],
                cate_sort: [
                    { required: true, message: '请输入排序编号', trigger: 'blur' }
                ],
                type: [
                    { required: true, message: '请选择课程分类', trigger: 'change' }
                ],
                cate_logo: [
                    {validator: checkTypeLogo, trigger: 'blur'}
                ]
            },
            rulesBind: {
                hire_no: [
                    { required: true, message: '请输入需要绑定的账户', trigger: 'blur' }
                ]
            },
            authValue: 0,
            formBind: {
                hire_no: ''
            },
            formLabelWidth: '80px',
            keyword: '',
            optionsShop: [],
            loading: false,
            shop_no: '',
            actionType: '',
            seller: {
                seller_id: '',
                seller_title: '',
                seller_logo: ''
            },
            word: '',
            pathName: '',
            backPage: ''
        };
    },
    created() {
        this.authResult = this.$route.meta.authResult;
        this.getParam();
        this.baseUrl = this.$baseUrl;
        this.mobileUrl = location.host == 'phaadmin.wxhand.com' ? 'http://class.zsdx.cn' : 'http://task.wxhand.com';
        this.$store.commit('SET_HEADER', [
            {
                title: "校园代理",
            },
            {
                title: '商城'
            },
            {
                title: '淘客店铺管理'
            }
        ]);
        this.getTableData();
    },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            vm.pathName = from.name;
        });
    },
    mounted() {
        if (window.history && window.history.pushState) {
            history.pushState(null, null, document.URL);
            window.addEventListener('popstate', this.goBack, false);
        }
    },
    destroyed(){
        window.removeEventListener('popstate', this.goBack, false);
    },
    methods: {
        /**
         * 监听返回事件
         */
        goBack () {
            this.$router.replace({
                name: this.pathName,
                query: {
                    page: this.backPage
                }
            });
        },

        /**
         * 获取url参数
         */
        getParam () {
            let query = this.$route.query;

            if (query.page !== undefined) {
                this.backPage = query.page;
            }
        },
        fnComputedName(name) {
            let result = '';

            this.optionsShop.map((item, index) => {
                if(name == item.shop_no) {
                    result = item.shop_title;
                }
            });
            return result;
        },
        remoteMethod(word) {
            if(word) {
                this.word = word;
            }
            if(word != '') {
                this.loading = true;
                this.$post('/student/shop%5Ccompany_suggest', {
                    keyword: this.word
                }, resp => {
                    if (resp.code == 1) {
                        this.optionsShop = resp.data.list;
                    }
                });
                this.loading = false;
            }else{
                this.optionsShop = [];
            }
        },
        fnCloseBindDialog() {
            this.bindDialogFlag = false;
            this.resetForm('formBind');
        },
        fnBindDialog(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if(this.actionType == 1) {
                        this.fnShopBind(this.shop_no, this.formBind.hire_no, ()=> {
                            this.$message({
                                type: 'success',
                                message: '操作成功',
                                center: true
                            });
                        });
                    }else if(this.actionType == 2) {
                        this.$post('/student/shop%5Cbind', {
                            hire_no: this.formBind.hire_no,
                            shop_no: this.shop_no
                        }, resp => {
                            if (resp.code == 1) {
                                this.$message({
                                    type: 'success',
                                    message: resp.msg,
                                    center: true
                                });
                                this.bindDialogFlag = false;
                                this.getTableData(this.page.now_page);
                            }
                        });
                    }else if(this.actionType == 3) {
                        this.$post('/student/shop%5Ccreate_tao', {
                            hire_no: this.formBind.hire_no,
                            seller_id: this.seller.seller_id,
                            seller_title: this.seller.seller_title,
                            seller_logo: this.seller.seller_logo,
                        }, resp => {
                            if (resp.code == 1) {
                                this.$message({
                                    type: 'success',
                                    message: resp.msg,
                                    center: true
                                });
                                this.bindDialogFlag = false;
                                this.getTableData(this.page.now_page);
                            }else{
                                this.$message({
                                    type: 'warning',
                                    message: resp.msg,
                                    center: true
                                });
                            }
                        });
                    }

                } else {
                    console.log(valid);
                    return false;
                }
            });
        },
        fnSetShopAuth(row) {
            this.shop_no = row.shop_no;
            this.authValue = row.need_audit;
            this.centerDialogVisible = true;
        },
        fnConfirmSetShopAuth() {
            this.$post('/student/shop%5Cmodify', {
                shop_no: this.shop_no,
                need_audit: this.authValue
            }, resp => {
                if (resp.code == 1) {
                    this.centerDialogVisible = false;
                    this.getTableData();
                    this.$message({
                        type: 'success',
                        message: '操作成功',
                        center: true
                    });
                }else{
                    this.$message({
                        type: 'warning',
                        message: resp.msg,
                        center: true
                    });
                }
            });
        },
        fnUploadImageOfGoods(e) {
            this.fnUploadImage(e, (resp) => {
                this.ruleForm.cate_logo = resp.data.url;
            }, (resp) => {
                console.log(resp.msg);
            });
        },
        fnUploadImage(e, success, error) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();

            pic.append('file', e.file);
            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                success: resp => {
                    if (resp.code == 1) {
                        success(resp);
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                        error(resp);
                    }
                }
            });
        },
        fnAddClick() {
            this.ruleForm = {
                cate_name: '',
                cate_sort: '',
                cate_no: '',
                cate_logo: ''
            };
            this.typeDisabled = false;
            this.dialogAddVisible = true;
        },
        fnEditClassify(row) {
            this.ruleForm = {
                cate_name: row.cate_name,
                cate_sort: row.cate_sort,
                cate_no: row.cate_no,
                cate_logo: row.cate_logo
            };
            this.dialogAddVisible = true;
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let data = {};

                    data.cate_no = this.ruleForm.cate_no;
                    data.cate_name = this.ruleForm.cate_name;
                    data.cate_sort = this.ruleForm.cate_sort;
                    data.cate_logo = this.ruleForm.cate_logo;
                    this.fnSetData(data);
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        fnSetData(data) {
            this.$post('/student/shop_goods_cate%5Csave', data, resp => {
                if (resp.code == 1) {
                    this.getTableData();
                    this.$message({
                        type: 'success',
                        message: '操作成功',
                        center: true
                    });
                    this.resetForm('ruleForm');
                    this.dialogAddVisible = false;
                }else{
                    this.$message({
                        type: 'warning',
                        message: resp.msg,
                        center: true
                    });
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        fnChangeClassifyStatus(row) {
            let status = row.cate_status == 1 ? 0 : 1;

            this.$post('/student/shop_goods_cate%5Cmodify', {
                cate_no: row.cate_no,
                cate_status: status
            }, resp => {
                if (resp.code == 1) {
                    this.$set(row, 'cate_status', status);
                    this.$message({
                        type: 'success',
                        message: '操作成功',
                        center: true
                    });
                }
            });
        },
        fnShopBind(shop_no, hire_no, cb) {
            this.$post('/student/shop%5Cbind', {
                shop_no: shop_no,
                hire_no: hire_no
            }, resp => {
                if (resp.code == 1) {
                    this.getTableData();
                    this.$message({
                        type: 'success',
                        message: '操作成功',
                        center: true
                    });
                }
            });
        },
        fnBindHireShop(row, type) {
            // 解绑
            if(type == 0) {
                this.$confirm('是否确定解绑该商家账户？', '确认解绑', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.fnShopBind(row.shop_no, '', null);
                }).catch(() => {
                });
            }else if(type == 1) { //绑定
                this.actionType = row.action_type;
                this.shop_no = row.shop_no;
                this.bindDialogFlag = true;
                // 创建并绑定
                if(row.action_type == 3) {
                    this.seller.seller_id = row.seller_id;
                    this.seller.seller_title = row.seller_title;
                    this.seller.seller_logo = row.seller_logo;
                }
            }else{
                console.log('type error');
            }
        },
        /**
         * 获取表格数据
         */
        getTableData(page) {
            this.$post('/student/shop%5Csearch', {
                page_id: page || this.page.page_id,
                keyword: this.keyword
            }, resp => {
                if (resp.code == 1) {
                    this.tableData = resp.data.list;
                    this.page.page_id = resp.data.page.now_page;
                    this.page.total_count = resp.data.page.total_count;
                    this.page.page_size = resp.data.page.page_size;
                    if (this.page.page_id > resp.data.page.total_page && this.page.page_id !== 1) {
                        this.getTableData(resp.data.page.total_page);
                    }
                }
            });
        },

        /**
         * 跳转页面
         */
        handleRoute(name, query) {
            let obj = {
                name
            };

            if (query) {
                obj.query = query;
            }

            this.$router.push(obj);
        },

        /**
         * 列表渲染辅助函数：列表项为空处理
         */
        emptyFormatter(row, column, val) {
            if (!val) {
                return '--';
            }
            return val;
        }
    }
};
</script>

<style lang="less" scoped>
.container {
    display: flex;
    flex-direction: column;
    width: 100%;
}
.add-dialog-input{
    width: 350px;
}
.operation-wrapper {
    display: flex;
    padding: 12px 23px;
    background-color: #fff;
    justify-content: space-between;
    .select-container{
        flex: 1;
    }
    .el-button {
        float: right;
        margin-left: 10px;
    }
}
.content-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin: 15px;
    overflow: hidden;
}
.search-wrapper {
    padding: 15px;
    background-color: #fff;
}
.filter-item {
    .el-form-item {
        margin-bottom: 0;
        white-space: nowrap;
    }
    .el-input {
        width: auto;
        vertical-align: middle;
    }
    .el-button {
        margin-left: 15px;
        vertical-align: middle;
    }
}
.table-wrapper {
    flex: 1;
    background-color: #fff;
    .sub-logo{
        width: 50px;
        height: 50px;
    }
}
.pagination-wrapper {
    padding-top: 10px;
    .el-pagination {
        float: right;
        padding: 0;
        background-color: transparent;
    }
}
</style>
<style lang="less">
.jingang-list-container {
    tbody {
        .cell {
            display: flex;
            align-items: center;
            height: 48px;
        }
    }
    .upload-good-image{
        border: 1px solid red;
        width: 100px;
        height: 100px;
        display: flex;
        border: 1px dashed #d9d9d9;
        border-radius: 4px;
        align-items: center;
        justify-content: center;
        font-size: 34px;
        color: #8c939d;
        img{
            width: 100px;
            height: 100px;
        }
    }
}
.auth-dialog{
    .dialog-auth{
        .auth-title{
            text-align: center;
            padding: 0 0 30px 0;
        }
        .radio-wrap-dialog{
            text-align: center;
        }
    }
}
</style>
